<?php

/*
 * core/db_pgsql.php
 *
 * database handler for postgresql
 */

// read comments in db.php for explanation


class PgSQL_DBConnector extends DBConnector {

    var $defaultPort = 5432;

    function PgSQL_DBConnector() { self::__construct(); }
    function __construct() 
    {
    }

    function __destruct() 
    {
    }

    function connect( $host, $port, $dbname, $user, $password )
    {
        $port = (is_null($port)) ? $this->defaultPort : $port;
        $connstr = "host='$host' port=$port dbname='$dbname' user='$user' password='$password'";

        $this->conn = pg_connect( $connstr );

        if( !$this->conn )
        {
            // we cannot set lastError here since we don't have the connection
            $this->conn = null;
            return false;
        }

        return true;
    }

    function disconnect()
    {
        if( is_null($this->conn) )
            Log::death( 'unable to disconnnect: not connected.' );

        @pg_close( $this->conn );
        $this->conn = null;
        return true;
    }

		function useDatabase( $dbName )
		{
			Log::death( 'function not implemented! work work...' );
			return false;
		}

    function select( $sql )
    {
        $result = @pg_query( $this->conn, $sql );

        if( !$result )
        {
            $this->setLastError( pg_last_error($this->conn) );
            return false;
        }

        return new PgSQL_DBResult( &$this, $result );
    }
    
    function execute( $sql )
    {
        if( !(@pg_query( $this->conn, $sql )) )
        {
            $this->setLastError( pg_last_error($this->conn) );
            return false;
        }
        return true;
    }

    function lastId( $table, $fieldname )
    {
            $sql = 'SELECT currval( pg_get_serial_sequence('."'".$table."','".$fieldname."'".') )';
            $r = $this->select( $sql );
            return $r->getVal('currval');
    } 

    function escapeStr( $txt )
    {
        return @pg_escape_string( $this->conn, $txt );
    }
}

class PgSQL_DBResult extends DBResult {

    function DBResult( &$connector, $resultset ) { self::__construct( &$connector, $resultset ); }
    function __construct( &$connector, $resultset )
    {
        parent::__construct( &$connector, $resultset );
    }

    function getNext()
    {
        if( !($this->row = @pg_fetch_array($this->resultSet, null, PGSQL_ASSOC)) )
        {
            $this->connector->setLastError( pg_last_error($this->connector->conn) );
            return false;
        }

        return $this->row;
    }

    function rowCount()
    {
        return @pg_num_rows( $this->resultSet );
    }

    function columnCount()
    {
        return @pg_num_fields( $this->resultSet );
    }

}


?>
